const mysql = require('mysql')
const path = require('path')
const fs = require('fs')
// 引入实现文件上传的第三方模块
const formidable = require('formidable')
// 用于生成token
const jwt = require('jsonwebtoken')

// 创建连接并添加配置
const conn = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'mydatabase'
})


module.exports = {
    getalldata(req, res) {
        // 创建sql语句
        let sql = `select * from heros where isdel = 0`
        // 调用方法执行sql语句并接收查询结果
        conn.query(sql, (error, results, fields) => {
            if (error) {
                res.json({
                    code: 500,
                    msg: '查询失败！'
                })
            } else {
                res.json({
                    code: 200,
                    msg: '查询成功！',
                    data: results
                })
            }
        })
    },
    uploadFile(req, res) {
        // 创建文件上传对象并添加配置
        const form = formidable({
            uploadDir: __dirname + '/public/images',
            keepExtensions: true
        });
        // 实现文件上传
        form.parse(req, (err, fields, files) => {
            if (err) {
                res.json({
                    code: 500,
                    msg: '文件上传失败！'
                })
            } else {
                console.log(files);
                let filePath = path.basename(files.img.path);
                console.log(filePath);
                res.json({
                    code: 200,
                    msg: '文件上传成功！',
                    img: filePath
                })
            }
        })
    },
    add(req, res) {
        // 接收客户端post请求的参数  body-parser使用
        console.log(req.body);
        if (!req.body.name) {
            return res.json({ code: 400, msg: 'name参数有误！' })
        }
        let sql = `insert into heros set ?`
        conn.query(sql, req.body, err => {
            if (err) {
                res.json({
                    code: 500,
                    msg: '英雄新增失败！'
                })
            } else {
                res.json({
                    code: 200,
                    msg: '英雄新增成功！'
                })
            }
        })
    },
    getHeroById(req, res) {
        console.log(req.query);
        let id = req.query.id
        let sql = `select * from heros where id =` + id
        conn.query(sql, (err, results) => {
            if (err) {
                res.json({ code: 500, msg: 'id参数有误！' })
            } else {
                res.json({
                    code: 200,
                    msg: '查询数据成功！',
                    data: results[0]
                })
            }
        })
    },
    edit(req, res) {
        console.log(req.body);
        if (!req.body.id) return res.json({ code: 400, msg: 'id参数未传递！' })
        let sql = `update heros set ? where id = ?`
        conn.query(sql, [req.body, req.body.id], err => {
            if (err) {
                res.json({
                    code: 500,
                    msg: '修改失败！'
                })
            } else {
                res.json({
                    code: 200,
                    msg: '修改成功！'
                })
            }
        })
    },
    delete(req, res) {
        if (!req.query.id) return res.json({ code: 400, msg: 'id参数有误！' })
        let sql = `update heros set isdel = 1 where id = ` + req.query.id
        conn.query(sql, err => {
            if (err) {
                res.json({ code: 500, msg: '删除失败！' })
            } else {
                res.json({ code: 200, msg: '删除成功！' })
            }
        })
    },
    getLoginPage(req, res) {
        fs.readFile(path.join(__dirname, '/views/login.html'), (err, data) => {
            if (err) return res.json({ code: 404 })
            res.end(data)
        })
    },
    login(req, res) {
        // console.log(req.body);
        let loginObj = req.body
        let sql = `select * from manager where username =  ?`
        conn.query(sql, [loginObj.username], (error, results) => {
            if (error) return res.json({ code: 500, m, msg: '服务器异常！' })
            if (results[0].username.length > 0) {
                if (loginObj.password == results[0].password) {
                    // 利用jsonwjebtokend模块生成toke并返回给客户端
                    const token = jwt.sign({ user: results[0] }, 'heros', { expiresIn: '3000s' })
                    res.json({
                        code: 200,
                        msg: '登陆成功！',
                        token: token
                    })
                } else {
                    res.json({ code: 500, msg: '密码输入有误！' })
                }
            } else {
                res.json({ code: 500, msg: '用户名不存在！' })
            }
        })
    }
}